<?php
require_once('TVB/pms/pdes/model/info_award.php');

class MisInfoAward
{
    private $mis_api;
    private $mis_pdes;
    private $error_msg = array();

    private $relation = array(
            'type'      => '', 
            'mis_id'    => '', 
            'mis_eid'   => '', 
            'mis_pid'   => '', 
            'pdes_id'   => '', 
            'pdes_eid'  => '', 
            'pdes_pid'  => ''
        );
	private $new;
	private $link_list;
	private $change_logs=array();

    function __construct(array $mis_pdes)
    {
        $this->relation = array_merge($this->relation, $mis_pdes);
        $this->relation['type'] = 'info_award';
        $this->mis_api = new MisApi();
        $this->mis_pdes = new mis_pdes();
    }

    public function import($award)
    {
		$this->new = FALSE;
		$this->link_list = array();
		$this->change_logs = array();

        if(!empty($award)) {
            foreach ($award as $mis_id) {
                $this->relation['mis_id'] = $mis_id;
                $param = array(
                    'co_code' => $this->relation['co_code'],
                    'type'      => 'info_award',
                    'mis_id'    => $mis_id
                );
                $relation = mis_pdes::getRelation($param);
                $mis_data = $this->mis_api->getDataByApi('getiAwardDetails', array('KEY_ID'=>$mis_id));
                $old_data = Model::$dbo['r']->findInstance('info_award',array($relation[0]['pdes_id']));

                if (!empty($relation)) {
                    $info_id = $this->getDiffResult($mis_data, $relation[0]['pdes_id']);
                } else {
					$this->new = TRUE;
                    $info_id =  $this->getDiffResult($mis_data);
                }
                $this->update_log($info_id,$mis_data,$old_data);
                $this->error_msg = array();
            }
            return TRUE;
        } else {
            $this->error_msg[] = 'info_award id not exist';
            return FALSE;
        }
    }


    private function update_log($e_id,$mis_data,$old_data)
    {
        $sync_data = array();
        $new_data  = array();
        $sql_data  = array();
        $error_msg = '';
        $log->pdes_id   = $e_id;
        $log->type      = 'info_award';
        try {
            $map = MisMapping::getMapping('info_award',$mis_data,'');
            if(!empty($old_data)) {
                $old_data->winners = CommonUtils::decode_field($old_data,'winners');
                $old_data->award_presenters = CommonUtils::decode_field($old_data,'award_presenters');
                $old_data->nominees = CommonUtils::decode_field($old_data,'nominees');
                $old_data->organizations = CommonUtils::decode_field($old_data,'organizations');
                $sync_data['Info_Award']   = MisMapping::formatLogData('info_award',(array)$old_data);
                #$sql_data[] = MisMapping::getRecoverSql('info_award',$old_data);
            }
            $new_data['Info_Award']    = MisMapping::formatLogData('info_award',(array)$map);
        } catch(MISException $e) {
            $error_msg = $e->getMessage();
            $this->error_msg[] = $e->getMessage();
        }
        # write log
        if(!empty($error_msg)) {
            $log->sync_data = '[]';
            $log->mis_data = '[]';
            $log->status    =  0;
            #$log->recover_sql = '[]';
            $log->message   = $this->getErrorMessage();
        } else {
            $log->sync_data = json_encode($sync_data);
            $log->mis_data = json_encode($new_data);
            $log->status    = $e_id > 0;
            #$log->recover_sql = json_encode($sql_data);
            $log->message   = $this->getErrorMessage();
            $log->modified_at = date('Y-m-d H:i:s',time());
        } 
        $ret =  mis_log::update($log);
        return $ret;

    }

    public function getErrorMessage()
    {
        return empty($this->error_msg) ? '' :trim( implode("\n",$this->error_msg));
    }

    private function getDiffResult($mis_info, $pdes_id='')
    {
        try {
            $integration_info = MisMapping::getMapping('info_award', $mis_info);
        } catch(MISException $e){
            $this->error_msg[] = $e->getMessage();
            return $pdes_id;
        }

        $info_award = new info_award;
        if ($pdes_id) {
            $pdes_info_award = $info_award->get($pdes_id);

            $new_info_award = Model::diff($pdes_info_award, $integration_info);
            foreach($integration_info as $key => $val) {
                if(array_key_exists($key,$pdes_info_award)) {
                    $val = (array)$val;
                    $new_info_award->$key = isset($val[0]) ? $val[0] : '';
                }
            }
    
            $new_info_award->winners = CommonUtils::format_field($new_info_award, 'winners');
            $new_info_award->nominees = CommonUtils::format_field($new_info_award, 'nominees');
            $new_info_award->award_presenters = CommonUtils::format_field($new_info_award, 'award_presenters');
            $new_info_award->organizations = CommonUtils::format_field($new_info_award, 'organizations');
            $new_info_award->modified_at = date('Y-m-d H:i:s');
            $new_info_award->status = AC::STATUS_NEW;

			if ($this->new === TRUE) {
	            Model::$dbo['w']->save($new_info_award);

				# change_log
				$this->change_logs[] = array(
					'type'=>'info_award',
					'keys' => array('id' => $pdes_id),
					'is_active'=>1,
					'is_publish'=>0,
					'episode_id'=>array($new_info_award->episode_id)
				);
			}

			$this->link_list[] = sprintf(AC::$mis_view_url, 'info_award', $pdes_id);
        } else {
            $episode = new episode;
            $episode_detail = $episode->get($this->relation['pdes_eid']);

            $info_award->set($info_award);
            $new_info_award = Model::diff($info_award, $integration_info);
            $tmp = array();
            foreach($integration_info as $key => $val) {
                if(array_key_exists($key,$info_award)) {
                    $val = (array)$val;
                    $new_info_award->$key = isset($val[0]) ? $val[0] : '';
                }
            }

            $new_info_award->winners = CommonUtils::format_field($new_info_award, 'winners');
            $new_info_award->nominees = CommonUtils::format_field($new_info_award, 'nominees');
            $new_info_award->award_presenters = CommonUtils::format_field($new_info_award, 'award_presenters');
            $new_info_award->organizations = CommonUtils::format_field($new_info_award, 'organizations');
         
            $new_info_award->episode_id = $this->relation['pdes_eid'];
            $new_info_award->publish_datetime = $episode_detail->publish_datetime;
            $new_info_award->expire_datetime = $episode_detail->expire_datetime;
            $new_info_award->status = AC::STATUS_NEW;
            $new_info_award->created_at = date('Y-m-d H:i:s');
            $new_info_award->modified_at = date('Y-m-d H:i:s');
            $pdes_id =  Model::$dbo['w']->save($new_info_award);
            $this->relation['pdes_id'] = $pdes_id;
            $this->mis_pdes->updateRelation($this->relation);

			# change_log
			$this->change_logs[] = array(
				'type'=>'info_award',
				'keys' => array('id' => $pdes_id),
				'is_active'=>1,
				'is_publish'=>0,
				'episode_id'=>array($new_info_award->episode_id)
			);
        }
        return $pdes_id;
    }

	public function getLinkList()
	{
		return $this->link_list;
	}
	public function getChangeLogs(){
		return $this->change_logs;
	}
}
?>
